package com.amoyhong.hongWhether.model;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/3/19.
 */
public class WeatherDataList {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd HH:mm");
    public List<WeatherData> weatherDatas = new ArrayList<>();
    ;

    public static class WeatherDataListDeserializer implements JsonDeserializer<WeatherDataList> {

        @Override
        public WeatherDataList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

            WeatherDataList weatherDataList = new WeatherDataList();

            JsonObject rootObject = json.getAsJsonObject();

            JsonArray jsonArray = rootObject.get("list").getAsJsonArray();

            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();

                long timeStamp = jsonObject.get("dt").getAsLong();

                Date date = new Date(timeStamp * 1000);

                String dateString = dateFormat.format(date);

                JsonObject mainObject = jsonObject.getAsJsonObject("main");
                double temperature = mainObject.get("temp").getAsDouble();

                JsonArray weatherArray = jsonObject.getAsJsonArray("weather");
                String description = weatherArray.get(0).getAsJsonObject().get("description").getAsString();

                WeatherData weatherData = WeatherData.newNoLocationWeatherData(date, dateString, description, temperature);

                weatherDataList.weatherDatas.add(weatherData);
            }

            return weatherDataList;
        }
    }

    @Override
    public String toString() {
        return "WeatherDataList{" +
                "weatherDatas=" + weatherDatas.size() +
                '}';
    }
}
